
package com.huaqin.punan;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class TextViewGPSActivity extends Activity {

    private Button btn_loc;
    private EditText myet;
    private TextView mytv;
    private ProgressDialog mProgressDialog;
    public static Context context;
    public static final String TAG = "TextViewGPSActivity";
    private LocationManager locationmanager;
    public static final String SMS_GETLOCATION_BROADCAST = "com.huaqin.gps.location";
    public static final int REQUEST_CODE_GETLOCATION = 0;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        context = this;
        registerReceiver(mBroadcastReceiver, new IntentFilter(SMS_GETLOCATION_BROADCAST));
        Log.e(TAG, "=====>>>onCreate");

        btn_loc = (Button) findViewById(R.id.mybtn);
        myet = (EditText) findViewById(R.id.myet);
        mytv = (TextView) findViewById(R.id.mytv);

        btn_loc.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                locationmanager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
                // 判断GPS是否正常启动
                if (!locationmanager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {

                    AlertDialog alert = new AlertDialog.Builder(context).setTitle("Open GPS")
                            .setMessage("open GPS to get Location?").setCancelable(false)
                            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Intent intents = new Intent(
                                            Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                    TextViewGPSActivity.this.startActivityForResult(intents,
                                            REQUEST_CODE_GETLOCATION);
                                }
                            }).setNegativeButton("NO", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            }).show();
                } else {
                    Intent intent_ser = new Intent();
                    intent_ser.setClass(TextViewGPSActivity.this, LocationService.class);
                    startService(intent_ser);

                    mProgressDialog = new ProgressDialog(context);
                    mProgressDialog.setTitle("Get Location");
                    mProgressDialog.setMessage("please wait...");
                    mProgressDialog.setCancelable(false);
                    mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                    mProgressDialog.show();

                }
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        if (requestCode == REQUEST_CODE_GETLOCATION && resultCode == 0) {
            String provider = Settings.Secure.getString(getContentResolver(),
                    Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
            if (provider != null && !provider.equals("")) {
                Intent intent_ser = new Intent();
                intent_ser.setClass(TextViewGPSActivity.this, LocationService.class);
                startService(intent_ser);
                Log.d(TAG, "Location providers:" + provider);

                mProgressDialog = new ProgressDialog(context);
                mProgressDialog.setTitle("Get Location");
                mProgressDialog.setMessage("please wait...");
                mProgressDialog.setCancelable(false);
                mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                mProgressDialog.show();

            } else {
                System.out.println("provider = null");
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            Boolean getLocation = intent.getBooleanExtra("GetLocation", false);
            Log.i(TAG, "getLocation=" + getLocation);
            if (getLocation) {
                // 获取地址成功

                String Longitude = intent.getStringExtra("Longitude");
                String Latitude = intent.getStringExtra("Latitude");

                String InsertStr = "[" + Longitude + "," + Latitude + "]";
                String OriginalStr = myet.getText().toString();
                String NewStr = OriginalStr + InsertStr;
                myet.setText(NewStr);
                myet.setSelection(NewStr.length());
                mProgressDialog.dismiss();
            } else {
                // 获取地址失败
                mProgressDialog.dismiss();

                AlertDialog alert = new AlertDialog.Builder(context).setTitle("Insert GPS")
                        .setMessage("get gps Location failed, use last Known Location?")
                        .setCancelable(false)
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                // 使用上次的地址
                                String bestProvider = locationmanager.getBestProvider(getCriteria(), true);
                                Location location = locationmanager.getLastKnownLocation(bestProvider);
                                if (location != null) {
                                    System.out.println("USE LAST KNOWN LOCATION!");
                                    String Longitude = String.valueOf(location.getLongitude());
                                    String Latitude = String.valueOf(location.getLatitude());

                                    String InsertStr = "[" + Longitude + "," + Latitude + "]";
                                    String OriginalStr = myet.getText().toString();
                                    String NewStr = OriginalStr + InsertStr;
                                    myet.setText(NewStr);
                                    myet.setSelection(NewStr.length());
                                } else {
                                    Toast.makeText(TextViewGPSActivity.this,
                                            "Get location failed!", Toast.LENGTH_SHORT).show();
                                    System.out.println("GET LAST KNOWN LOCATION FAILED!");
                                }

                                dialog.dismiss();
                            }
                        }).setNegativeButton("NO", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        }).show();

            }
            //unregisterReceiver(mBroadcastReceiver);
        }
    };

    /**
     * 返回查询条件
     * 
     * @return
     */
    private Criteria getCriteria() {
        Criteria criteria = new Criteria();
        // 设置定位精确度 Criteria.ACCURACY_COARSE比较粗略，Criteria.ACCURACY_FINE则比较精细
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        // 设置是否要求速度
        criteria.setSpeedRequired(false);
        // 设置是否允许运营商收费
        criteria.setCostAllowed(false);
        // 设置是否需要方位信息
        criteria.setBearingRequired(false);
        // 设置是否需要海拔信息
        criteria.setAltitudeRequired(false);
        // 设置对电源的需求
        criteria.setPowerRequirement(Criteria.POWER_LOW);
        return criteria;
    }

    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        Log.e(TAG, "=====>>>onStart");
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        Log.e(TAG, "=======>>>onResume");
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        Log.e(TAG, "=====>>>onPause");
    }

    @Override
    protected void onRestart() {
        // TODO Auto-generated method stub
        super.onRestart();
        Log.e(TAG, "=====>>>onRestart");
    }

    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
        Log.e(TAG, "===>>>onStop");
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(mBroadcastReceiver);
        super.onDestroy();
        Log.e(TAG, "!!!>>>onDestroy");
    }

}
